﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RRHH.RRHH_Service;
using System.Threading;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using RENIEC.Entities;

namespace RRHH.Controllers
{
    public class PersonalEFController : Controller
    {
        private RRHH.RRHH_Service.RRHHServiceClient serviceRRHH = new RRHH.RRHH_Service.RRHHServiceClient();

        // GET: /PersonalEF/
        public ActionResult ListadoPersonal()
        {
            return View(serviceRRHH.ListarPersonal());
        }

        // GET: /PersonalEF/Details/5
        public ActionResult Details(int id = 0)
        {
            BEPersonal personal = new BEPersonal();
            personal = serviceRRHH.ObtenerPersonal(id);

            if (personal == null)
            {
                return HttpNotFound();
            }
            return View(personal);
        }

        // GET: /PersonalEF/Create
        public ActionResult Create()
        {
            using (RRHH_Service.RRHHServiceClient wsRRHH = new RRHHServiceClient())
            {
                ViewData["ddEstCivil"] = new SelectList(wsRRHH.ListarEstadosCivil().ToList(), "IDESTADOCIVIL", "DESCRIPCION");
                ViewData["ddlDepartamento"] = new SelectList(wsRRHH.ListDepartamento().ToList(), "IDDEPARTAMENTO", "DESCRIPCION");

                ViewData["ddlProvincia"] = new SelectList(new[] { "-Selecciona-" });
                ViewData["ddlDistrito"] = new SelectList(new[] { "-Selecciona-" });
                LLenarComboSexo();
                return View();
            }
        }

        [ActionName("DepartamentoPorProvincia")]
        public ActionResult GetDepartamentoPorProvincia(string id)
        {
            List<BEProvincia> provincias = null;
            using (RRHH_Service.RRHHServiceClient wsRRHH = new RRHHServiceClient())
            {
                int x = Int32.Parse(id);
                provincias = wsRRHH.ListProvincia(x).ToList();
                return new JsonResult() { Data = provincias };
            }
        }

        [HttpPost]
        public ActionResult GetProvincia(string depa)
        {

            List<BEProvincia> lstProv = new List<BEProvincia>();

            int dep = int.Parse(depa);

            using (RRHH_Service.RRHHServiceClient wsRRHH = new RRHHServiceClient())
            {
                lstProv = wsRRHH.ListProvincia(dep).ToList();

                if (lstProv == null)
                    throw new ArgumentException("Departamento incorrecto");

                Thread.Sleep(1000);

            }

            return Json(lstProv);

        }


        private void LLenarComboSexo()
        {
            List<Sexo> lst = new List<Sexo>();
            lst.Add(new Sexo() { id = 0, sexo = "Masculino" });
            lst.Add(new Sexo() { id = 0, sexo = "Femenino" });

            ViewData["ddlSexo"] = new SelectList(lst.ToList(), "id", "sexo");
        }

        // POST: /PersonalEF/Create
        [HttpPost]
        public ActionResult Create(BEPersonal personal, string ddEstCivil, string ddlSexo)
        {

            if (ModelState.IsValid)
            {
                using (RRHH_Service.RRHHServiceClient wsRRHH = new RRHHServiceClient())
                {
                    personal.IDDEPDOMICILIO = 15;
                    personal.IDPROVDOMICILIO = 1;
                    personal.IDDISTDOMICILIO = 2;
                    personal.IDDOCIDENTIDAD = 1; // se setea 1 porque es el ID de DNI de la tabla DOCUMENTOIDENTIDAD
                    personal.ANULADO = "0";
                    personal.FLAGESTADO = "1";
                    personal.NUMERODOCUMENTO = personal.NUMERODOCUMENTO ;
                    personal.FLAGSEXO = ddlSexo;
                    personal.IDESTADOCIVIL = int.Parse(ddEstCivil);

                    wsRRHH.CrearPersonal(personal);
                    return RedirectToAction("ListadoPersonal");
                }
            }
            
            
            return View(personal);
        }

        [HttpPost]
        public JsonResult GetData()
        {
            List<int> result = new List<int>() { 1, 4, 5 };
            return Json(result);
        }

        // POST: /PersonalEF/Create
        [HttpPost]
        public JsonResult ConsultarDNI(string dni)
        {
            JsonResult result;
            try
            {
                //Consumo del servicio REST
                //Se valida si existe o no el DNI
                string url = @"http://localhost:2488/Reniec.svc/persona/" + dni;

                WebRequest req = WebRequest.Create(url);

                req.Method = "GET";

                HttpWebResponse res = req.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string personaJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                BEReniec PersonaReniec = js.Deserialize<BEReniec>(personaJson);

                if (PersonaReniec.DNI == null)
                {
                    result = new JsonResult()
                    {
                        // Probably include a more detailed error message.
                        Data = new { Error = true, ErrorMessage = "The DNI is not valid." }
                    };
                    return result;
                };

                return Json(PersonaReniec, JsonRequestBehavior.AllowGet);

            }
            catch (Exception)
            {
                result = new JsonResult()
                {
                    // Probably include a more detailed error message.
                    Data = new { Error = true, ErrorMessage = "The DNI is not valid." }
                };
            }

            return result;

        }

        // GET: /PersonalEF/Edit/5
        public ActionResult Edit(int id = 0)
        {
            BEPersonal personal = new BEPersonal();
            personal = serviceRRHH.ObtenerPersonal(id);

            if (personal == null)
            {
                return HttpNotFound();
            }
            serviceRRHH.ModificarPersonal(personal.IDPERSONAL, personal.NOMBRESEMPLEADO, personal.APEPATERNOEMPLEADO, personal.APEMATERNOEMPLEADO);
            return View(personal);
        }

        // POST: /PersonalEF/Edit/5
        [HttpPost]
        public ActionResult Edit(BEPersonal personal)
        {
            if (ModelState.IsValid)
            {

                serviceRRHH.ModificarPersonal(personal.IDPERSONAL, personal.NOMBRESEMPLEADO, personal.APEPATERNOEMPLEADO, personal.APEMATERNOEMPLEADO);
                return RedirectToAction("ListadoPersonal");
            }
            return View(personal);
        }

        // GET: /PersonalEF/Delete/5
        public ActionResult Delete(int id = 0)
        {
            BEPersonal personal = new BEPersonal();
            personal = serviceRRHH.ObtenerPersonal(id);

            if (personal == null)
            {
                return HttpNotFound();
            }
            return View(personal);
        }

        // POST: /PersonalEF/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            serviceRRHH.EliminarPersonal(id);
            return RedirectToAction("ListadoPersonal");
        }

        //protected override void Dispose(bool disposing)
        //{
        //    db.Dispose();
        //    base.Dispose(disposing);
        //}


        public class Sexo
        {
            public int id { get; set; }
            public string sexo { get; set; }
        }
    }
}